<template>
  <a-card :bordered="false">
    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="48">
          <a-col :md="8" :sm="24">
            <a-form-item label="唯一标识">
              <a-input v-model="queryParam.id" placeholder="请输入唯一标识" />
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <a-form-item label="名字及电话">
              <a-input v-model="queryParam.phone" placeholder="请输入名字及电话" style="width: 100%" />
            </a-form-item>
          </a-col>
          <!-- <a-col :md="8" :sm="24">
            <a-form-item label="类型">
              <a-select v-model="queryParam.type" placeholder="请选择" default-value="0">
                <a-select-option value="0">父级</a-select-option>
                <a-select-option value="1">子级</a-select-option>
              </a-select>
            </a-form-item>
          </a-col> -->
          <template v-if="advanced">
            <!--
            <a-col :md="8" :sm="24">
              <a-form-item label="分类名称">
                <a-input v-model="queryParam.flName" style="width: 100%" />
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="父级分类">
                <a-select
                  show-search
                  style="width: 100%"
                  :filter-option="filterOption"
                  v-model="queryParam.parentId"
                  :allowClear="true"
                >
                  <a-select-option v-for="(action, index) in RolesLists" :key="index" :value="action.value">
                    {{ action.label }}
                  </a-select-option>
                </a-select>
              </a-form-item> </a-col
            >-->
            <!-- <a-col :md="8" :sm="24">
              <a-form-item label="昵称">
                <a-input v-model="queryParam.nickname" style="width: 100%" />
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="电话">
                <a-input v-model="queryParam.phone" style="width: 100%" />
              </a-form-item>
            </a-col> -->
            <!-- <a-col :md="8" :sm="24">
              <a-form-item label="更新日期">
                <a-date-picker v-model="queryParam.date" style="width: 100%" placeholder="请输入更新日期" />
              </a-form-item>
            </a-col> -->
            <!-- <a-col :md="8" :sm="24">
              <a-form-item label="性别">
                <a-select v-model="queryParam.sex" placeholder="请选择">
                  <a-select-option value="0">男</a-select-option>
                  <a-select-option value="1">女</a-select-option>
                  <a-select-option value="2">未知</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="github账号">
                <a-input v-model="queryParam.github_login" style="width: 100%" />
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="gitee账号">
                <a-input v-model="queryParam.gitee_login" style="width: 100%" />
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="邮箱">
                <a-input v-model="queryParam.email" style="width: 100%" />
              </a-form-item>
            </a-col> -->
          </template>
          <a-col :md="(!advanced && 8) || 24" :sm="24">
            <span
              class="table-page-search-submitButtons"
              :style="(advanced && { float: 'right', overflow: 'hidden' }) || {}"
            >
              <a-button type="primary" @click="search">查询</a-button>
              <a-button style="margin-left: 8px" @click="() => (this.queryParam = {})">重置</a-button>
              <a @click="toggleAdvanced" style="margin-left: 8px">
                {{ advanced ? '收起' : '展开' }}
                <a-icon :type="advanced ? 'up' : 'down'" />
              </a>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <div class="table-operator">
      <a-button type="primary" icon="plus" @click="insertRole">新增</a-button>
      <a-popconfirm
        v-if="selectedRowKeys.length > 0"
        title="是否删除这些用户?"
        ok-text="是"
        cancel-text="否"
        @confirm="confirm(selectedRowKeys)"
        @cancel="cancel"
      >
        <a-button type="primary" icon="delete">批量删除</a-button>
      </a-popconfirm>
    </div>
    <a-table
      :loading="loading"
      :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
      rowKey="id"
      ref="table"
      size="default"
      :columns="columns"
      :data-source="loadData"
      @expand="handleExpand"
      :scroll="{ x: 1000 }"
    >
      <span slot="specification" slot-scope="specification">
        <a-tag v-for="item in specification" :key="item">{{ item }}</a-tag>
      </span>
      <!-- <span slot="remark" slot-scope="remark">
        {{remark}}
      </span> -->
      <span slot="price" slot-scope="price">
        <span>{{ price }}</span>
      </span>
      <span slot="serviceCarousel" slot-scope="serviceCarousel">
        <!-- <a-tag v-for="item in serviceCarousel" :key="item">{{ item }}</a-tag> -->
        <!-- {{ serviceCarousel }} -->
        <img
          v-for="item in serviceCarousel"
          :key="item.uid"
          :src="item.url"
          style="width: 50px; height: 50px"
          alt="图片未加载！"
          srcset=""
        />
      </span>
      <span slot="servicedetails" slot-scope="servicedetails">
        <!-- <a-tag v-for="item in servicedetails" :key="item">{{ item }}</a-tag> -->
        <!-- {{ servicedetails }} -->
        <img
          v-for="item in servicedetails"
          :key="item.uid"
          :src="item.url"
          style="width: 50px; height: 50px"
          alt="图片未加载！"
          srcset=""
        />
      </span>
      <!-- <span v-if="parentName" slot="parentName" slot-scope="parentName">
        <a-tag>{{ parentName.flName }}</a-tag>

      </span> -->
      <!-- <span slot="status" slot-scope="status">
        <a-tag>{{ status | statusFilter }}</a-tag>

      </span>
      <span slot="avatar" slot-scope="avatar" style="width: 200px">
        <img v-if="avatar" style="width: 55px; height: 55px" :src="avatar | avatarfilter" alt="" />
        <img v-else style="width: 55px; height: 55px" :src="defaultimg" alt="" />
      </span> -->

      <template slot="roles" slot-scope="roles">
        <a-tag v-for="item in roles" :key="item.value">{{ item.label }}</a-tag>
      </template>
      <span slot="action" slot-scope="text, record">
        <a @click="$refs.modal.edit(record)">编辑</a>
        <a-divider type="vertical" />
        <!-- <a @click="editpermission(record)">权限</a>
        <a-divider type="vertical" /> -->
        <a-popconfirm
          title="是否删除这个用户?"
          ok-text="是"
          cancel-text="否"
          @confirm="confirm(record)"
          @cancel="cancel"
        >
          <a href="javascript:;">删除</a>
        </a-popconfirm>
      </span>
    </a-table>

    <role-modal ref="modal" @ok="handleOk"></role-modal>
    <div>
      <a-drawer
        title="菜单及权限"
        placement="right"
        :closable="false"
        :visible="drawerVisible"
        :after-visible-change="afterVisibleChange"
        @close="onClose"
      >
        <a-tree
          checkable
          @select="onSelect"
          @check="onCheck"
          :tree-data="treeData"
          show-icon
          default-expand-all
          :checked-keys="defalutSelect"
          :check-strictly="true"
        >
          <!-- <a-icon slot="smile" type="smile-o" />
          <a-icon slot="meh" type="smile-o" /> -->
          <!-- <a-icon slot="switcherIcon" type="down" /> -->
          <template slot="custom" slot-scope="e">
            <!-- {{ e }} -->
            <!-- <a-icon :type="e.checked ? 'smile-o' : 'setting'" /> -->
            <a-icon :type="e.dataRef.icon" />
          </template>
        </a-tree>
      </a-drawer>
    </div>
  </a-card>
  <!-- 抽屉 -->
</template>

<script>
import { STable } from '@/components'
import RoleModal from './modules/EmployeesModal'

// const SEX = {
//   0: '男',
//   1: '女',
//   2: '未知'
// }
const STATUS = {
  0: '开启',
  1: '禁用'
}
const TYPE = {
  0: '父级',
  1: '子级'
}

export default {
  name: 'TableList',
  components: {
    STable,
    RoleModal
  },
  data() {
    return {
      // 高级搜索 展开/关闭
      RolesLists: [],
      defaultimg: require('@/assets/defaultimg.jpg'),
      defalutSelect: [],
      treeData: [],
      loading: false,
      drawerVisible: false,
      replaceFields: {
        children: 'child',
        title: 'name'
      },
      description:
        '列表使用场景：后台管理中的权限管理以及角色管理，可用于基于 RBAC 设计的角色权限控制，颗粒度细到每一个操作类型。',

      visible: false,
      table: {
        role: '',
        value: '2'
      },

      form: null,
      mdl: {},

      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {},
      // 表头
      columns: [
        {
          title: '唯一识别码',
          dataIndex: 'id',
          align: 'center',
          width: 200,
          fixed: 'left',
          key: 'id'
        },
        // {
        //   title: '用户名',
        //   dataIndex: 'username',
        //   align: 'center',
        //   fixed: 'left',
        //   key: 'left'
        // },
        {
          title: '电话即名称',
          dataIndex: 'phone',
          align: 'center',
          width: 300,
          key: 'phone'
        },
        // {
        //   title: '服务详情名称',
        //   dataIndex: 'remark',
        //   align: 'center',
        //   width: 300,
        //   key: 'remark'
        // },
        // {
        //   title: '服务价格',
        //   dataIndex: 'price',
        //   align: 'center',
        //   scopedSlots: { customRender: 'price' },
        //   sorter: (a, b) => a.price - b.price,
        //   width: 300,
        //   key: 'price'
        // },
        // {
        //   title: '类型',
        //   dataIndex: 'type',
        //   scopedSlots: { customRender: 'type' },
        //   width: 100,
        //   align: 'center',
        //   key: 'type'
        // },
        // {
        //   title: '状态',
        //   dataIndex: 'status',
        //   scopedSlots: { customRender: 'status' },
        //   width: 100,
        //   align: 'center',
        //   key: 'status'
        // },
        // {
        //   title: '规格',
        //   dataIndex: 'specification',
        //   align: 'center',
        //   width: 300,
        //   scopedSlots: { customRender: 'specification' },
        //   key: 'specification'
        // },
        // {
        //   title: '服务轮播图',
        //   dataIndex: 'serviceCarousel',
        //   width: 400,
        //   align: 'center',
        //   scopedSlots: { customRender: 'serviceCarousel' },
        //   key: 'serviceCarousel'
        // },
        // {
        //   title: 'gitee账号',
        //   dataIndex: 'giteeLogin',
        //   width: 100,
        //   align: 'center',
        //   key: 'giteeLogin'
        // },
        // {
        //   title: '电话',
        //   dataIndex: 'phone',
        //   align: 'center',
        //   key: 'phone',
        //   width: 200
        // },
        // {
        //   title: '服务图片',
        //   dataIndex: 'servicedetails',
        //   align: 'center',
        //   key: 'servicedetails',
        //   scopedSlots: { customRender: 'servicedetails' },
        //   width: 400
        // },
        // {
        //   title: '已售数量',
        //   dataIndex: 'quantitysold',
        //   align: 'center',
        //   key: 'quantitysold',
        //   width: 100
        // },
        // {
        //   title: '绑定的角色',
        //   dataIndex: 'roles',
        //   scopedSlots: { customRender: 'roles' },
        //   align: 'center',
        //   width: 100,
        //   key: 'roles'
        // },
        // {
        //   title: '创建时间',
        //   dataIndex: 'createTime',
        //   scopedSlots: { customRender: 'createTime' },

        //   defaultSortOrder: 'descend',
        //   sorter: (a, b) => a.createTime - b.createTime,
        //   align: 'center'
        // },
        {
          title: '操作',
          width: '150px',
          dataIndex: 'action',
          fixed: 'right',
          scopedSlots: { customRender: 'action' },
          align: 'center',
          key: 'action'
        }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: [],
      selectedRowKeys: [],
      selectedRows: [],
      Roleid: ''
    }
  },
  created() {
    this.getTable()
    // this.getsyspression()
    // this.loadPermissions()
  },
  filters: {
    typeFilter(key) {
      return TYPE[key]
    },
    rolesFilter(key) {
      return key.map((item) => {
        return item.label
      })
    },
    statusFilter(key) {
      return STATUS[key]
    },
    moment(value) {
      return new Date(value).toLocaleString() // 你可以根据需要修改格式
    },
    avatarfilter(e) {
      return JSON.parse(e).url
    }
  },
  methods: {
    filterOption(input, option) {
      // console.log('input', input)
      // console.log('option', option)

      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    loadPermissions() {
      // const that = this
      // console.log(that)
      this.$http
        .get('/servicedetails/serviceParent')
        .then((res) => {
          // console.log('下拉权限', res)
          if (res.code === 200) {
            this.RolesLists = res.result
            // console.log('数据', this.RolesLists)
          }
        })
        .catch((err) => {
          console.log('出错', err)
        })
    },
    toggleAdvanced() {
      this.advanced = !this.advanced
    },
    getsyspression() {
      const pages = {
        pageNo: 0,
        pageSize: 10,
        params: {
          id: '',
          createTime: '',
          remarks: '',
          type: 0,
          parentId: '',
          name: '',
          englishName: '',
          path: '',
          code: '',
          outerChain: 0,
          icon: '',
          sort: 0,
          children: [
            {
              id: '',
              createTime: '',
              remarks: '',
              type: 0,
              parentId: '',
              name: '',
              englishName: '',
              path: '',
              code: '',
              outerChain: 0,
              icon: '',
              sort: 0,
              children: [{}],
              tree: true
            }
          ],
          tree: true
        }
      }
      this.$http.post('/sysPermission/page', pages).then((res) => {
        if (res.code === 200) {
          console.log('选择数据', res.result.records)
          const aa = this.convertToTreeData(res.result.records)
          console.log('树结构数据', aa)

          this.treeData = aa
        }
      })
    },
    convertToTreeData(rawData) {
      // 树形装换
      return rawData.map((item) => {
        const transformedItem = {
          title: item.name, // 使用 name 字段作为 title
          key: item.id, // 使用 id 作为 key
          scopedSlots: { icon: 'custom' }, // 自定义图标插槽
          icon: item.icon || 'smile', // 使用 icon 字段，如果没有则为空
          children: item.children ? this.convertToTreeData(item.children) : null // 递归处理子节点
        }
        return transformedItem
      })
    },
    onSelect(selectedKeys, info) {
      console.log('selected', selectedKeys, info)
    },
    onCheck(checkedKeys, info) {
      console.log('onCheck', checkedKeys, info)
      this.defalutSelect = checkedKeys.checked
      const aak = {
        roleId: this.Roleid,
        check: info.checked,
        permission_id: checkedKeys.checked
      }
      this.$http.post('/sysRole/check', aak).then((res) => {
        console.log('是否成功', res)
      })
      console.log('角色及权限', aak)
    },
    afterVisibleChange(val) {
      // console.log('drawerVisible', val)
    },
    onClose() {
      this.drawerVisible = false
    },
    editpermission(e) {
      this.drawerVisible = true
      console.log('角色id', e)
      this.Roleid = e.id
      this.$http.get(`/sysRole/getPermission/${e.id}`).then((res) => {
        // console.log('选中的数据', res)
        if (res.code === 200) {
          this.defalutSelect = res.result
        }
        // console.log('数据', this.defalutSelect)
      })
    },

    confirm(e) {
      // console.log(111, e)
      var value = []
      if (Object.prototype.toString.call(e) === '[object Object]') {
        // console.log('单个删除')
        value.push(e.id)
      } else {
        value = e
      }
      // console.log(222, this.selectedRowKeys)
      console.log(value)
      this.$http.delete('/employees/delete', { data: value }).then((res) => {
        if (res.code === 200) {
          this.$message.success('删除成功')
          this.getTable()
        }
      })

      // this.$message.success('Click on Yes')
    },
    cancel(e) {
      console.log(e)
      // this.$message.error('Click on No')
    },

    insertRole() {
      this.$refs.modal.add()
    },
    search() {
      console.log('查询参数', Object.keys(this.queryParam))
      if (Object.keys(this.queryParam).length > 0) {
        const roleList = this.removeSpacesFromObject(this.queryParam)
        // console.log(roleList)
        this.loading = true
        this.$http.post('/employees/tjSearch', roleList).then((res) => {
          if (res.code === 200) {
            this.loadData = []
            this.loading = false
            this.loadData = res.result
          }
        })
      } else {
        this.getTable()
      }
    },
    reTable() {
      console.log(this.table)
      this.table = {
        role: '',
        value: '2'
      }
    },
    removeSpacesFromObject(obj) {
      // 去除对象中的每一项数据的空格
      // console.log('obj', obj)

      const newObj = {}
      Object.keys(obj).forEach((key) => {
        newObj[key] = obj[key].replace(/\s+/g, '') // 去除所有空格
      })
      return newObj
    },
    handleExpand(expanded, record) {},
    plsc() {
      console.log('批量删除')
    },
    onSelectChange(selectedRowKeys) {
      // console.log('selectedRowKeys changed: ', selectedRowKeys)
      this.selectedRowKeys = selectedRowKeys
    },
    getTable() {
      this.loading = true

      this.$http.get('/employees/list').then((res) => {
        if (res.code === 200) {
          this.loading = false
          console.log('数据', res)

          this.loadData = res.result
          // this.expandedRowKeys = res.result.map((item) => item.id)
        }
      })
    },
    handleEdit(record) {
      this.mdl = Object.assign({}, record)

      this.mdl.permissions.forEach((permission) => {
        permission.actionsOptions = permission.actionEntitySet.map((action) => {
          return { label: action.describe, value: action.action, defaultCheck: action.defaultCheck }
        })
      })

      console.log(this.mdl)
      this.visible = true
    },
    handleOk() {
      this.getTable()
      this.$refs.modal.close()
      // 新增/修改 成功时，重载列表
      // this.$refs.table.refresh()
    },
    onChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    }
  },
  watch: {
    /*
      'selectedRows': function (selectedRows) {
        this.needTotalList = this.needTotalList.map(item => {
          return {
            ...item,
            total: selectedRows.reduce( (sum, val) => {
              return sum + val[item.dataIndex]
            }, 0)
          }
        })
      }
      */
  }
}
</script>
